// 创建浮动工具栏和功能面板
function injectUI() {
  // 注入样式
  const link = document.createElement('link');
  link.rel = 'stylesheet';
  link.type = 'text/css';
  link.href = chrome.runtime.getURL('content/content.css');
  document.head.appendChild(link);

  // 创建工具栏容器
  const toolbar = document.createElement('div');
  toolbar.id = 'tiger-dict-selection-toolbar';
  toolbar.style.display = 'none';
  toolbar.innerHTML = `
    <button class="tiger-dict-toolbar-btn" id="tiger-dict-translate-btn" title="翻译选中文字">
      <svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 24 24"><path fill="currentColor" d="m12.87 15.07l-2.54-2.51l.03-.03A17.5 17.5 0 0 0 14.07 6H17V4h-7V2H8v2H1v1.99h11.17C11.5 7.92 10.44 9.75 9 11.35C8.07 10.32 7.3 9.19 6.69 8h-2c.73 1.63 1.73 3.17 2.98 4.56l-5.09 5.02L4 19l5-5l3.11 3.11zM18.5 10h-2L12 22h2l1.12-3h4.75L21 22h2zm-2.62 7l1.62-4.33L19.12 17z"/></svg>
    </button>
  `;

  // 创建遮罩层
  const overlay = document.createElement('div');
  overlay.id = 'tiger-dict-overlay';
  overlay.style.display = 'none';

  // 创建翻译结果面板
  const panel = document.createElement('div');
  panel.id = 'tiger-dict-translation-panel';
  panel.style.display = 'none';
  panel.className = 'tiger-dict-translation-card';
  panel.innerHTML = `
    <div class="tiger-dict-panel-header">
      <button class="tiger-dict-close-btn" id="tiger-dict-close-panel" title="关闭">×</button>
    </div>
    <div class="tiger-dict-panel-content">
      <div class="tiger-dict-loading">正在翻译...</div>
      <div class="tiger-dict-translation-result" style="display:none;">
        <div class="tiger-dict-word-info">
          <h3 id="tiger-dict-translated-word"></h3>
          <p id="tiger-dict-phonetic" class="phonetic"></p>
        </div>
        <div class="tiger-dict-translation-details">
          <p id="tiger-dict-translation"></p>
        </div>
        <div class="tiger-dict-word-explains" id="tiger-dict-word-explains"></div>
        <div class="tiger-dict-word-examples" id="tiger-dict-word-examples"></div>
        <button class="tiger-dict-add-btn" id="tiger-dict-add-word-btn">添加到单词本</button>
      </div>
      <div class="tiger-dict-error-message" style="display:none;">
        <p>翻译失败，请稍后再试</p>
      </div>
    </div>
  `;

  // 添加到页面
  document.body.appendChild(toolbar);
  document.body.appendChild(overlay);
  document.body.appendChild(panel);

  // 设置事件监听
  setupEventListeners(toolbar, panel, overlay);
}

// 设置事件监听器
function setupEventListeners(toolbar, panel, overlay) {
  let currentSelection = '';

  // 监听文本选择
  document.addEventListener('mouseup', function (e) {
    setTimeout(() => {
      const selection = window.getSelection().toString().trim();

      if (selection && selection.length > 0) {
        currentSelection = selection;
        showToolbar(e, toolbar, selection);
      } else {
        hideToolbar(toolbar);
      }
    }, 100);
  });

  // 工具栏按钮事件 - 使用事件委托
  toolbar.addEventListener('click', (e) => {
    if (e.target.closest('#tiger-dict-translate-btn')) {
      showTranslationPanel(panel, overlay, currentSelection);
      translateText(currentSelection, panel);
    }
  });

  // 关闭面板 - 使用事件委托
  panel.addEventListener('click', (e) => {
    if (e.target.closest('#tiger-dict-close-panel')) {
      hidePanel(panel, overlay);
    }

    if (e.target.closest('#tiger-dict-add-word-btn')) {
      addWordToVocabulary(currentSelection, panel);
    }
  });

  overlay.addEventListener('click', () => hidePanel(panel, overlay));

  // 点击页面其他地方隐藏工具栏和面板
  document.addEventListener('click', function (e) {
    const toolbarElement = document.getElementById(
      'tiger-dict-selection-toolbar'
    );
    const panelElement = document.getElementById(
      'tiger-dict-translation-panel'
    );

    if (
      toolbarElement &&
      !toolbarElement.contains(e.target) &&
      e.target !== toolbarElement
    ) {
      hideToolbar(toolbarElement);
    }

    if (
      panelElement &&
      !panelElement.contains(e.target) &&
      e.target.id !== 'tiger-dict-translate-btn' &&
      toolbarElement &&
      !toolbarElement.contains(e.target)
    ) {
      hidePanel(panelElement, overlay);
    }
  });
}

// 显示工具栏
function showToolbar(e, toolbar, selection) {
  const range = window.getSelection().getRangeAt(0);
  const rect = range.getBoundingClientRect();

  // 检查选区是否有效
  if (rect.width === 0 && rect.height === 0) {
    return;
  }

  toolbar.style.left = rect.left + window.scrollX + 'px';
  toolbar.style.top = Math.max(rect.top + window.scrollY - 40, 0) + 'px';
  toolbar.style.display = 'flex';
  toolbar.style.position = 'absolute';
  toolbar.style.zIndex = '10000';

  // 存储选中的文本
  toolbar.setAttribute('tiger-dict-data-selection', selection);
}

// 隐藏工具栏
function hideToolbar(toolbar) {
  toolbar.style.display = 'none';
}

// 显示翻译面板
function showTranslationPanel(panel, overlay, selection) {
  // 显示面板和遮罩
  panel.style.display = 'block';
  overlay.style.display = 'block';

  // 定位面板
  const toolbar = document.getElementById('tiger-dict-selection-toolbar');
  if (toolbar) {
    const rect = toolbar.getBoundingClientRect();

    panel.style.left = rect.left + window.scrollX + 'px';
    panel.style.top =
      Math.max(rect.top + rect.height + +window.scrollY, 0) + 'px';
    panel.style.position = 'absolute';
    panel.style.zIndex = '10001';
  }

  // 重置面板内容
  const loadingElement = panel.querySelector('.tiger-dict-loading');
  const resultElement = panel.querySelector('.tiger-dict-translation-result');
  const errorElement = panel.querySelector('.tiger-dict-error-message');
  const addButton = panel.querySelector('.tiger-dict-add-btn');

  loadingElement.style.display = 'block';
  resultElement.style.display = 'none';
  errorElement.style.display = 'none';
  addButton.textContent = '添加到单词本';
  addButton.disabled = false;

  // 隐藏工具栏
  hideToolbar(document.getElementById('tiger-dict-selection-toolbar'));
}

// 隐藏面板
function hidePanel(panel, overlay) {
  panel.style.display = 'none';
  overlay.style.display = 'none';
}

// SHA256加密函数
async function sha256(message) {
  // 使用Web Crypto API进行SHA256加密
  const msgBuffer = new TextEncoder().encode(message);
  const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
}

// 生成有道API签名
async function generateSign(query, appKey, salt, curtime, secretKey) {
  // 根据有道API文档，signType=v3时签名规则为：
  // sha256(应用ID+input+salt+curtime+应用密钥)
  // input为：q的前10个字符 + q的长度 + q的后10个字符(当q长度大于20)或q字符串(当q长度小于等于20)

  let input = query;
  if (query.length > 20) {
    input =
      query.substring(0, 10) +
      query.length +
      query.substring(query.length - 10);
  }

  const str = appKey + input + salt + curtime + secretKey;
  return await sha256(str);
}

// 调用有道翻译API
async function translateText(text, panel) {
  try {
    // 从存储中获取应用ID和应用密钥
    const { youdaoAppKey = '', youdaoSecret = '' } =
      await chrome.storage.local.get(['youdaoAppKey', 'youdaoSecret']);

    if (!youdaoAppKey || !youdaoSecret) {
      // 如果没有配置应用ID或应用密钥，则显示错误信息
      showError(panel, '请先在扩展设置中配置有道词典应用ID和应用密钥');
      return;
    }

    // 通过background script发送请求以避免CORS问题
    const response = await chrome.runtime.sendMessage({
      action: 'translate',
      data: {
        text: text,
        appKey: youdaoAppKey,
        secret: youdaoSecret,
      },
    });

    if (response.error) {
      showError(panel, response.error);
      return;
    }

    if (response.data.errorCode === '0') {
      displayTranslation(response.data, panel);
    } else {
      showError(panel, '翻译失败，请检查应用ID和应用密钥是否正确');
    }
  } catch (error) {
    console.error('翻译出错:', error);
    showError(panel, '网络错误，请稍后再试: ' + error.message);
  }
}

// 显示翻译结果
function displayTranslation(data, panel) {
  const loadingElement = panel.querySelector('.tiger-dict-loading');
  const resultElement = panel.querySelector('.tiger-dict-translation-result');
  const errorElement = panel.querySelector('.tiger-dict-error-message');

  loadingElement.style.display = 'none';
  resultElement.style.display = 'block';
  errorElement.style.display = 'none';

  // 显示翻译结果
  const wordElement = panel.querySelector('#tiger-dict-translated-word');
  const phoneticElement = panel.querySelector('#tiger-dict-phonetic');
  const translationElement = panel.querySelector('#tiger-dict-translation');
  const explainsElement = panel.querySelector('#tiger-dict-word-explains');
  const examplesElement = panel.querySelector('#tiger-dict-word-examples');

  wordElement.textContent = data.query;

  if (data.basic && data.basic.phonetic) {
    phoneticElement.textContent = '/' + data.basic.phonetic + '/';
    phoneticElement.style.display = 'block';
  } else {
    phoneticElement.style.display = 'none';
  }

  if (data.translation) {
    translationElement.textContent = data.translation.join('; ');
  } else {
    translationElement.textContent = '无翻译结果';
  }

  // 显示单词释义
  if (data.basic && data.basic.explains) {
    let explainsHTML = '<h4>释义</h4><ul>';
    data.basic.explains.forEach((explain) => {
      explainsHTML += `<li>${explain}</li>`;
    });
    explainsHTML += '</ul>';
    explainsElement.innerHTML = explainsHTML;
    explainsElement.style.display = 'block';
  } else {
    explainsElement.style.display = 'none';
  }

  // 显示例句
  if (data.web) {
    let examplesHTML = '<h4>例句</h4><ul>';
    // 最多显示3个例句
    const examplesToShow = data.web.slice(0, 3);
    examplesToShow.forEach((item) => {
      examplesHTML += `<li><p><strong>${item.key}</strong></p>`;
      examplesHTML += `<p>${item.value.join(', ')}</p></li>`;
    });
    examplesHTML += '</ul>';
    examplesElement.innerHTML = examplesHTML;
    examplesElement.style.display = 'block';
  } else {
    examplesElement.style.display = 'none';
  }
}

// 显示错误信息
function showError(panel, message = '翻译失败，请稍后再试') {
  const loadingElement = panel.querySelector('.tiger-dict-loading');
  const resultElement = panel.querySelector('.tiger-dict-translation-result');
  const errorElement = panel.querySelector('.tiger-dict-error-message');
  const errorMessage = panel.querySelector('.tiger-dict-error-message p');

  loadingElement.style.display = 'none';
  resultElement.style.display = 'none';
  errorElement.style.display = 'block';
  errorMessage.textContent = message;
}

// 添加单词到词汇表（模拟）
async function addWordToVocabulary(word, panel) {
  const addButton = panel.querySelector('#tiger-dict-add-word-btn');
  const originalText = addButton.textContent;

  try {
    addButton.textContent = '添加中...';
    addButton.disabled = true;

    // 获取单词的翻译信息
    const wordElement = panel.querySelector('#tiger-dict-translated-word');
    const phoneticElement = panel.querySelector('#tiger-dict-phonetic');
    const translationElement = panel.querySelector('#tiger-dict-translation');
    const explainsElement = panel.querySelector('#tiger-dict-word-explains');

    const question = wordElement ? wordElement.textContent : word;
    let answer = '';

    if (translationElement && translationElement.textContent) {
      answer += translationElement.textContent + '\n';
    }

    if (phoneticElement && phoneticElement.textContent) {
      answer += phoneticElement.textContent + '\n';
    }

    if (explainsElement && explainsElement.textContent) {
      answer += explainsElement.textContent;
    }

    // 通过 background script 发送请求到 TigerDeck
    const response = await chrome.runtime.sendMessage({
      action: 'addWordToTigerDeck',
      data: {
        question: question,
        answer: answer,
      },
    });

    if (response.error) {
      throw new Error(response.error);
    }

    // 成功响应
    addButton.textContent = '添加成功';

    // 2秒后恢复按钮状态
    setTimeout(() => {
      if (addButton) {
        addButton.textContent = originalText;
        addButton.disabled = false;
      }
    }, 2000);
  } catch (error) {
    console.error('添加单词失败:', error);
    if (addButton) {
      addButton.textContent = '添加失败：' + error.message;
      setTimeout(() => {
        addButton.textContent = originalText;
        addButton.disabled = false;
      }, 2000);
    }
  }
}

// 初始化
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', injectUI);
} else {
  injectUI();
}
